/* include signal */
#include	"common.h"

Sigfunc *signal(int signo, Sigfunc *func)
{
	struct sigaction	act, oact;

	act.sa_handler = func;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	if (signo == SIGALRM) {
#ifdef	SA_INTERRUPT
		act.sa_flags |= SA_INTERRUPT;	/* SunOS 4.x */
#endif
	} else {
#ifdef	SA_RESTART
		act.sa_flags |= SA_RESTART;		/* SVR4, 44BSD */
#endif
	}
	if (sigaction(signo, &act, &oact) < 0)
		return(SIG_ERR);
	return(oact.sa_handler);
}
/* end signal */

Sigfunc *Signal(int signo, Sigfunc *func)	/* for our signal() function */
{
	Sigfunc	*sigfunc;

	if ( (sigfunc = signal(signo, func)) == SIG_ERR)
		err_sys("signal error");
	return(sigfunc);
}


void sig_chld(int signo){
	pid_t pid;
	int stat;
	
	while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0)
		fprintf(stderr, "child %d terminated\n", pid);
	return;
}

void sig_engine(){
	int res = 0;

	Signal(SIGALRM, sig_dispatcher);
	
	struct itimerval tick;
	memset(&tick, 0, sizeof(tick));

	/* Timeout to run function first time  */
	tick.it_value.tv_sec = 10;
	tick.it_value.tv_usec = 0;
	
	/* Interval time to run function   */
	tick.it_interval.tv_sec = 10; /* sec */
	tick.it_interval.tv_usec = 0; /* micro sec */
	/* Set timer, ITIMER_REAL : real-time to decrease timer, */
	                         /* send SIGALRM when timeout   */
	res = setitimer(ITIMER_REAL, &tick, NULL);
	if(res){
		fprintf(stderr, "Set timer failed!!\n");
	}

	while(1){
		pause();
	}
	exit(0);
}

void sig_dispatcher(){
	pthread_t d_id = 0, h_id = 0;
	int ret;
	
	if(gDispatcher & DISPATCH_DEFENSE){
		ret = pthread_create(&d_id, NULL, (void *)Defense, NULL);
	}
	if(gDispatcher & DISPATCH_HEART){
		ret = pthread_create(&h_id, NULL, (void *)Heart, NULL);
	}
	if(d_id){
		pthread_join(d_id, NULL);
		gDispatcher |= DISPATCH_DEFENSE;
	}
	if(h_id){
		pthread_join(h_id, NULL);
		gDispatcher |= DISPATCH_HEART;	
	}

}
